package com.qf.web.common.ascpet;

import com.qf.common.base.exception.ServiceException;
import com.qf.common.base.result.ResultCode;
import com.qf.web.common.annotations.UpdateRedisCache;
import com.qf.web.common.utils.RedisKeyUtils;
import com.qf.web.dao.BaseRedisDao;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author 51993
 */
@Aspect
@Component
public class ClearCacheAspect {

    @Autowired
    BaseRedisDao baseRedisDao;

    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.qf.web.common.annotations.UpdateRedisCache)")
    public void pointCut(){

    }

    /**
     * 定义环绕通知，当更新完数据后清除Redis中的缓存信息
     * @param joinPoint
     * @return
     */
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint){
        Object obj = null;
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        UpdateRedisCache updateRedisCache = method.getAnnotation(UpdateRedisCache.class);
        //获取key
        String key = RedisKeyUtils.getCacheKey(method,joinPoint.getArgs(),updateRedisCache.keyPrefix());
        //执行业务逻辑
        try {
            obj = joinPoint.proceed();
        } catch (Throwable e) {
            throw new ServiceException(ResultCode.BUSINESS_UNKNOW_ERROR);
        }
        //业务逻辑正常执行后，清除redis中的缓存信息
        baseRedisDao.delete(key);
        return obj;
    }


}
